package org.biz.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.biz.common.CommonConstant;
import org.biz.common.Result;
import org.biz.modules.entity.*;
import org.biz.modules.mapper.SysUserMapper;
import org.biz.modules.service.SysDocUserService;
import org.biz.modules.service.SysRoleService;
import org.biz.modules.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zf
 * @ClassName SysUserServiceImpl
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysDocUserService sysDocUserService;

    @Value("${data.year}")
    private String dataYear;

    private static final String FINISH = "完成";
    private static final String UNFINISH = "未完成";
    private static final String TOTAL = "total";
    private static final String PASSED = "passed";
    private static final String PROGRESS = "progress";


    @Override
    public IPage<SysUser> getPage(Page<SysUser> page, QueryParams queryParams) {
        IPage<SysUser> page1 = sysUserMapper.getPage(page, queryParams);
        List<SysUser> records = page1.getRecords();
        for (SysUser user : records) {
            Map<String, Object> result2Map = getResult2(user.getId());
            int intValue = MapUtils.getIntValue(result2Map, PASSED);
            String progress = MapUtils.getString(result2Map, PROGRESS);
            user.setPassed(intValue);
            user.setProgress(progress);
        }
        return page1;
    }



    @Override
    public List<SysUser> getExportList(QueryParams queryParams) {
        Page<SysUser> page = new Page<>(1, Integer.MAX_VALUE,false);
        IPage<SysUser> page1 = sysUserMapper.getPage(page, queryParams);
        List<SysUser> records = page1.getRecords();

        if (CollectionUtils.isNotEmpty(records)) {
            //所有用户填报进度
            List<SysDocUser> allUserfinishTextList = sysUserMapper.getTitleFinishNumByUserId(null);
            Map<String, List<SysDocUser>> userDocMap = allUserfinishTextList.stream()
                    .collect(Collectors.groupingBy(SysDocUser::getUserId));

            // 获取所有学员的身份证
            List<String> userIdCards = records.stream()
                    .map(SysUser::getIdCard)
                    .collect(Collectors.toList());
            // 分批查询学习记录
            List<LearningRecord> learningRecordList = new ArrayList<>();
            int pageSize = 10000; // 每次查询10000条
            int totalPages = (int) Math.ceil((double) userIdCards.size() / pageSize);
            for (int pageNumber = 0; pageNumber < totalPages; pageNumber++) {
                int offset = pageNumber * pageSize;
                List<String> pageIdCards = userIdCards.subList(offset, Math.min(offset + pageSize, userIdCards.size()));
                List<LearningRecord> batchLearningRecords = sysUserMapper.getLearningRecordPageList(pageIdCards);
                learningRecordList.addAll(batchLearningRecords);
            }

            // 按照 idNumber 进行分组
            Map<String, List<LearningRecord>> groupedByIdNumberMap = learningRecordList.stream()
                    .collect(Collectors.groupingBy(LearningRecord::getIdNumber));
            for (SysUser user : records) {
                //匹配某一学员的填报信息
                setDocToExcel(userDocMap, user);
                //某一学员的所有课程
                List<LearningRecord> learningRecords = groupedByIdNumberMap.get(user.getIdCard());
                if (CollectionUtils.isEmpty(learningRecords)) {
                    user.setPassed(0);
                    user.setProgress("0%");
                }else{
                    Map<String, Object> result2Map = getResultMap(learningRecords);
                    int intValue = MapUtils.getIntValue(result2Map, PASSED);
                    String progress = MapUtils.getString(result2Map, PROGRESS);
                    user.setPassed(intValue);
                    user.setProgress(progress);
                }
            }
        }

        return records;
    }

    private void setDocToExcel(Map<String, List<SysDocUser>> userDocMap, SysUser user) {
        List<SysDocUser> userDocs = userDocMap.getOrDefault(user.getId(), Collections.emptyList());
        for (SysDocUser doc : userDocs) {
            //根据查询的填报项下标，拼成和实体类SysUser的属性名一致
            String fieldName = "doc" + doc.getTitleId() + "_" + doc.getTextIndex();
            try {
                Field field = SysUser.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                //1.1、2.1、2.2三 题不需要填数字，上传附件表格中就以 “ 是 ” 标注 ，没传就空
                if (StringUtils.equals(fieldName,"doc1_1") && doc.getFinishNum() == 1){
                    user.setDoc1_1("是");
                }
                else if (StringUtils.equals(fieldName,"doc2_1") && doc.getFinishNum() == 1){
                    user.setDoc2_1("是");
                }
                else if (StringUtils.equals(fieldName,"doc2_2") && doc.getFinishNum() == 1){
                    user.setDoc2_2("是");
                }
                else {
                    //反射添加
                    field.set(user, doc.getValue1());
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // 忽略未定义字段
                System.out.println("字段不存在：" + fieldName);
            }
        }
    }

    @Override
    public List<SysItem> getDepartmentList(String departName) {
        if (StringUtils.isNotBlank(departName)) {
            return sysUserMapper.getBaseHospitalListByName(departName);
        }else{
            return sysUserMapper.getDepartmentList();
        }
    }

    @Override
    public List<SysHospital> getHospitalList(String cityName,String name) {
        if (StringUtils.isNotBlank(cityName) || StringUtils.isNotBlank(name)) {
            return sysUserMapper.getHospitalListByName(cityName,name);
        }else{
            return sysUserMapper.getCityList();
        }
    }

    @Override
    public int updateDeadline(String deadline) {
        return sysUserMapper.updateDeadline(deadline);
    }

    @Override
    public boolean isUpdate(String userId) {
        String deadline = sysUserMapper.getDeadline();
        if (StringUtils.isBlank(deadline)){
            throw new RuntimeException("材料提交截止日期未配置，请联系超级管理员！");
        }
        //退回以后可以无视截止时间继续填报并且保存
        SysUser user = this.getById(userId);
        if (user != null && StringUtils.equals(user.getStatus(),CommonConstant.UNFINISHED) && StringUtils.equals(user.getBack(),CommonConstant.BACK)){
            return true;
        }
        String nowDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        LocalDate now = LocalDate.parse(nowDate);
        LocalDate deadline2 = LocalDate.parse(deadline);
        //当前日期在截止日期之前，都可编辑材料
        return now.isBefore(deadline2) || now.isEqual(deadline2);
    }

    @Override
    public boolean isAdmin(String userId) {
        List<SysRole> roleList = sysRoleService.getRoleListByUserId(userId);
        List<String> roleCodeList = roleList.stream().map(SysRole::getRoleCode).collect(Collectors.toList());
        //管理员
        return roleCodeList.contains(CommonConstant.ADMIN) || roleCodeList.contains(CommonConstant.SUPER_ADMIN);
    }

    @Override
    public List<SysDocTitle> getDocTitleList(String userId) {
        //填报项模板
        List<SysDocTitle> docTitleList = sysUserMapper.getDocTitleList();
        //用户填报进度
        List<SysDocUser> finishTextList = sysUserMapper.getTitleFinishNumByUserId(userId);
        //按填报项分组，求完成的条数，k-四大项，v-完成填空的条数
        Map<String, Integer> groupTitleMap = finishTextList.stream()
                .collect(Collectors.groupingBy(SysDocUser::getTitleId, Collectors.summingInt(SysDocUser::getFinishNum)));
        for (SysDocTitle title : docTitleList) {
            String titleId = title.getId();
            title.setFinishNum(MapUtils.getIntValue(groupTitleMap,titleId));

            //（一）临床专业实践（以下条目，第1-3条为必备条件，第4-7条满足其中1条）
            if (StringUtils.equals(titleId, CommonConstant.ONE)) {
                //1-3条完成数量
                Map<String, Integer> groupTitleMap1_3 = finishTextList.stream()
                        .filter(v->StringUtils.equals(titleId, CommonConstant.ONE) && v.getTextIndex()<=3)
                        .collect(Collectors.groupingBy(SysDocUser::getTitleId, Collectors.summingInt(SysDocUser::getFinishNum)));
                //4-7条完成数量
                Map<String, Integer> groupTitleMap4_7 = finishTextList.stream()
                        .filter(v->StringUtils.equals(titleId, CommonConstant.ONE) && v.getTextIndex()>=4)
                        .collect(Collectors.groupingBy(SysDocUser::getTitleId, Collectors.summingInt(SysDocUser::getFinishNum)));
                boolean isFinish1_3 = false;
                boolean isFinish4_7 = false;
                //第1-3条为必备条件，三条都需完成
                if(MapUtils.getIntValue(groupTitleMap1_3,titleId) == 3){
                    isFinish1_3 = true;
                }
                //第4-7条满足其中1条
                if(MapUtils.getIntValue(groupTitleMap4_7,titleId) >= 1){
                    isFinish4_7 = true;
                }
                //同时满足两种情况才算完成这一项
                if (isFinish1_3 && isFinish4_7) {
                    title.setFinish(true);
                }
            }

            //（二）临床教学与科研（以下条目，第1-4条满足其中2条，第5-8条满足其中1条）
            if (StringUtils.equals(titleId, CommonConstant.TWO)) {
                //1-4条完成数量
                Map<String, Integer> groupTitleMap1_4 = finishTextList.stream()
                        .filter(v->StringUtils.equals(titleId, CommonConstant.TWO) && v.getTextIndex()<=4)
                        .collect(Collectors.groupingBy(SysDocUser::getTitleId, Collectors.summingInt(SysDocUser::getFinishNum)));
                //5-8条完成数量
                Map<String, Integer> groupTitleMap5_8 = finishTextList.stream()
                        .filter(v->StringUtils.equals(titleId, CommonConstant.TWO) && v.getTextIndex()>=5)
                        .collect(Collectors.groupingBy(SysDocUser::getTitleId, Collectors.summingInt(SysDocUser::getFinishNum)));
                boolean isFinish1_4 = false;
                boolean isFinish5_8 = false;
                //第1-4条满足其中2条
                if(MapUtils.getIntValue(groupTitleMap1_4,titleId) >= 2){
                    isFinish1_4 = true;
                }
                //第5-8条满足其中1条
                if(MapUtils.getIntValue(groupTitleMap5_8,titleId) >= 1){
                    isFinish5_8 = true;
                }
                //同时满足两种情况才算完成这一项
                if (isFinish1_4 && isFinish5_8) {
                    title.setFinish(true);
                }
            }
            //（三）临床质量管理,完成的条数和总数相同，才算完成这一项
            if (StringUtils.equals(titleId, CommonConstant.THREE) &&
                    MapUtils.getIntValue(groupTitleMap,title.getId()) == title.getTitleTotal()) {
                title.setFinish(true);
            }

            //（四）专业发展：去除系统生成的第一条完成近5年内专科护士继续教育平台规定的课程和考核=总数-1
            if (StringUtils.equals(titleId, CommonConstant.FOUR)) {
                title.setTitleTotal(title.getTitleTotal()-1);
            }
            //（四）专业发展,去除近5年内专科护士继续教育平台规定的课程和考核 且另外1条已完成，才算完成这一项
            if (StringUtils.equals(titleId, CommonConstant.FOUR) &&
                    MapUtils.getIntValue(groupTitleMap,title.getId()) == title.getTitleTotal()
//                    && FINISH.equals(getResult(userId))
            ) {
                title.setFinish(true);
            }
        }
        return docTitleList;
    }

    /**
    *（四）专业发展 1.完成近5年内专科护士继续教育平台规定的课程和考核
    *
     * @return 完成/未完成
     *
     * @param userId*/
//    private String getResult(String userId){
//        SysUser sysUser = sysUserMapper.selectOne(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId, userId));
//        if (sysUser == null){
//            return UNFINISH;
//        }
//        String idNumber = sysUser.getIdCard();
//        List<LearningRecord> records = getLearningRecord(idNumber);
//        if (CollectionUtils.isEmpty(records)) {
//            return UNFINISH;
//        }
//        //课程总数
//        int total = records.size();
//        //完成的课程数
//        int passedCount = records.stream().mapToInt(LearningRecord::getIsPass).sum();
//        if (total == passedCount) {
//            System.out.println("用户:"+userId+FINISH);
//            return FINISH;
//        }else{
//            System.out.println("用户:"+userId+UNFINISH);
//            return UNFINISH;
//        }
//    }
    private Map<String,Object> getResult2(String userId){
        Map<String, Object> resultMap = new HashMap<>();
        SysUser sysUser = sysUserMapper.selectOne(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId, userId));
        if (sysUser == null || (sysUser != null && StringUtils.isBlank(sysUser.getIdCard()))){
            resultMap.put(TOTAL, 0);
            resultMap.put(PASSED, 0);
            resultMap.put(PROGRESS, "0%");
            return resultMap;
        }
        String idNumber = sysUser.getIdCard();
        List<LearningRecord> records = getLearningRecord(idNumber);
        if (CollectionUtils.isEmpty(records)) {
            resultMap.put(TOTAL, 0);
            resultMap.put(PASSED, 0);
            resultMap.put(PROGRESS, "0%");
            return resultMap;
        }
        return getResultMap(records);
    }

//    private Map<String, Object> getInitProcessMap() {
//        Map<String, Object> resultMap = new HashMap<>();
//        //课程总数
//        int total = 0;
//        //完成的课程数
//        int passed = 0;
//        //学习进度= 完成的课程数/课程总数
//        String progress = "0%";
//        resultMap.put(TOTAL, total);
//        resultMap.put(PASSED, passed);
//        resultMap.put(PROGRESS, progress);
//        return resultMap;
//    }

    private Map<String, Object> getResultMap(List<LearningRecord> records) {
        Map<String, Object> resultMap = new HashMap<>();
        int total;
        int passed;
        total = records.size();
        passed = records.stream().mapToInt(LearningRecord::getIsPass).sum();
        BigDecimal totalDecimal = BigDecimal.valueOf(total);
        BigDecimal passedDecimal = BigDecimal.valueOf(passed);
        BigDecimal divide = passedDecimal.divide(totalDecimal,2,BigDecimal.ROUND_HALF_UP);
        BigDecimal multiply = divide.multiply(BigDecimal.valueOf(100));
        resultMap.put(TOTAL, total);
        resultMap.put(PASSED, passed);
        resultMap.put(PROGRESS, multiply.intValue()+"%");
        return resultMap;
    }


    @Override
    public List<SysDocUser> getTitleText(String titleId, String userId) {
        //填报内容模板
        List<SysDocTitleText> texts = sysUserMapper.getTitleText(titleId);
        List<SysDocUser> docUserList = new ArrayList<>();
        for (SysDocTitleText text : texts) {
            SysDocUser docUser = new SysDocUser();
            docUser.setTitleId(text.getTitleId());
            docUser.setText2(text.getText2());
            docUser.setText(text.getIndex()+"."+text.getText());
            docUser.setTitle(text.getTitle());
            docUser.setTextIndex(text.getIndex());
            docUserList.add(docUser);
        }
        //用户填空的值
        List<SysDocUser> docUsers = sysUserMapper.getTitleFinishNumByUserId(userId);
//        if (CollectionUtils.isNotEmpty(docUsers)) {
            for (SysDocUser user :docUserList) {
                for (SysDocUser value : docUsers) {
                    //填报项+第几条填空匹配，添加用户值
                    if (StringUtils.equals(user.getTitleId(), value.getTitleId()) &&
                            user.getTextIndex() == value.getTextIndex()) {
                        user.setId(value.getId());
                        user.setValue1(value.getValue1());
                        user.setValue2(value.getValue2());
                        user.setFile(value.getFile());
                        user.setFinishNum(value.getFinishNum());
                        if (value.getFinishNum() == 1) {
                            user.setFinish(true);
                        }
                    }
                }
                //非用户填写
                //（四）专业发展 1.完成近5年内专科护士继续教育平台规定的课程和考核 是否完成
                if (StringUtils.equals(user.getTitleId(), CommonConstant.FOUR) &&
                        user.getTextIndex() == 1){
//                    String result = getResult(userId);
                    Map<String, Object> resultMap = getResult2(userId);
                    int total = MapUtils.getIntValue(resultMap, TOTAL);
                    int passed = MapUtils.getIntValue(resultMap, PASSED);
                    String msg = "";
                    if (total == 0){
                        msg = ",无法检测到专科护士账号";
                    }
                    //非用户填写，单独添加完成状态
                    user.setValue1("总课程:"+total+",已学完:"+passed+msg);
                    if (total == passed){
                        user.setFinish(true);
                    }
//                    //如果完成，则添加完成标记1
//                    if (FINISH.equals(result)){
//                        user.setFinishNum(1);
//                    }
                }

//            }
        }
        return docUserList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> saveOrUpdate(List<SysDocUser> docs, String userId) {
        List<SysDocUser> saveList = new ArrayList<>();
        for (SysDocUser userDoc : docs) {
            userDoc.setUpdateTime(LocalDateTime.now());
            userDoc.setCreateTime(LocalDateTime.now());
            //没有任何填空内容，不插入
            if (StringUtils.isBlank(userDoc.getValue1()) && StringUtils.isBlank(userDoc.getValue2()) && StringUtils.isBlank(userDoc.getFile())) {
                continue;
            }
            //（四）专业发展 1.完成近5年内专科护士继续教育平台规定的课程和考核
            if (StringUtils.equals(userDoc.getTitleId(),CommonConstant.FOUR) && userDoc.getTextIndex() == 1){
                //系统自动生成的，不记录入库
                continue;
            }
            saveList.add(userDoc);
        }
        List<SysDocUser> list = sysDocUserService.list(new LambdaQueryWrapper<SysDocUser>().eq(SysDocUser::getUserId, userId));
        List<String> deleteList = list.stream().map(SysDocUser::getId).collect(Collectors.toList());
        //删除该用户所有记录
        if (CollectionUtils.isNotEmpty(deleteList)) {
            sysDocUserService.removeByIds(deleteList);
        }
        boolean saveOrUpdate = sysDocUserService.saveOrUpdateBatch(saveList);
        if (saveOrUpdate) {
            return Result.OK("保存成功！");
        }else {
            return Result.error("保存失败！");
        }
    }

    /**
    *是否完成所有填报内容
    *
     **/
    private boolean isFinishAllDoc(String userId){
        List<SysDocTitle> docTitleList = this.getDocTitleList(userId);
        if (CollectionUtils.isNotEmpty(docTitleList)) {
            //完成所有填报项数量
            int allFinish = 0;
            for (SysDocTitle title : docTitleList) {
                if (title.isFinish()) {
                    allFinish += 1;
                }
            }
            //完成所有填报项数量=填报项总数,视为完成了所有资料的填报
            if (allFinish == docTitleList.size()) {
                System.out.println("用户："+userId+"填报完成");
                return true;
            }
        }
        return false;
    }


    @Override
    public UserCountVO getCountByStatus(String name) {
        List<SysUser> nurseList = sysUserMapper.getNurseList(name,dataYear);
        if (CollectionUtils.isEmpty(nurseList)) {
            return new UserCountVO();
        }
        //待审核人数
        long stationOther = nurseList.stream().filter(u ->StringUtils.equals(u.getStation(), CommonConstant.STATION_OTHER)).count();
        //已通过人数
        long passed = nurseList.stream().filter(u ->StringUtils.equals(u.getStatus(), CommonConstant.PASSED)).count();
        long fail = nurseList.stream().filter(u ->StringUtils.equals(u.getStatus(), CommonConstant.FAIL)).count();
        long unfinished = nurseList.stream().filter(u -> StringUtils.equals(u.getLevel(),CommonConstant.LEVEL) && StringUtils.equals(u.getStatus(), CommonConstant.UNFINISHED)).count();
        long auth = nurseList.stream().filter(u -> StringUtils.equals(u.getLevel(),CommonConstant.LEVEL)).count();

        UserCountVO vo = new UserCountVO();
        vo.setFail(fail);
        vo.setPassed(passed);
        vo.setUnfinished(unfinished);
        vo.setTotal(nurseList.size());
        vo.setStationOther(stationOther);
        vo.setAuth(auth);
        return vo;
    }

    @Override
    public List<LearningRecord> getLearningRecord(String idNumber) {
        return sysUserMapper.getLearningRecord(idNumber);
    }

    @Transactional(rollbackFor = Exception.class)
    public void setSubjectFinish(String idNumber, Long subjectId) {
        Long id = sysUserMapper.selectUidInHomecare(idNumber);
        sysUserMapper.mockLearingRecord(id, subjectId);
        sysUserMapper.setSubjectFinish(id, subjectId);
    }

    /**
     *
     *是否完成基本信息、承诺书、汇总表的填写
     **/
    @Override
    public StatusVO getFinishStatusByUserId(String userId) {
        StatusVO vo = new StatusVO();
        SysUser user = sysUserMapper.selectById(userId);
        //承诺书
        String promise = user.getPromise();
        //汇总表
        String summary = user.getSummary();
        String avatar = user.getAvatar();
        String name = user.getName();
        String idCard = user.getIdCard();
        String mobile = user.getMobile();
        String hospital = user.getHospital();
        String department = user.getDepartment();
        String baseHospital = user.getBaseHospital();
        String trainYear = user.getTrainYear();
        String certificateDate = user.getCertificateDate();
//        String currentDepart = user.getCurrentDepart();
        String duty = user.getDuty();
//        String certificate = user.getCertificate();
        Integer age = user.getAge();
        String sex = user.getSex();
        String certificateNum = user.getCertificateNum();
        String title = user.getTitle();
        String educationLevel = user.getEducationLevel();
        String degree = user.getDegree();
        String station = user.getStation();

        String hospitalHistory = user.getHospitalHistory();
        String dutyHistory = user.getDutyHistory();
        String titleHistory = user.getTitleHistory();
        String educationLevelHistory = user.getEducationLevelHistory();
        String degreeHistory = user.getDegreeHistory();
        String stationHistory = user.getStationHistory();

        if (StringUtils.isNotBlank(avatar) &&
                StringUtils.isNotBlank(name) &&
                StringUtils.isNotBlank(idCard) &&
                StringUtils.isNotBlank(mobile) &&
                StringUtils.isNotBlank(hospital) &&
                StringUtils.isNotBlank(department) &&
                StringUtils.isNotBlank(baseHospital) &&
                StringUtils.isNotBlank(trainYear) &&
                StringUtils.isNotBlank(certificateDate) &&
//                StringUtils.isNotBlank(currentDepart) &&
                StringUtils.isNotBlank(duty) &&
//                StringUtils.isNotBlank(certificate) &&
                age != null &&
                StringUtils.isNotBlank(sex) &&
                StringUtils.isNotBlank(certificateNum) &&
                StringUtils.isNotBlank(title) &&
                StringUtils.isNotBlank(educationLevel) &&
                StringUtils.isNotBlank(degree) &&
                StringUtils.isNotBlank(hospitalHistory) &&
                StringUtils.isNotBlank(dutyHistory) &&
                StringUtils.isNotBlank(titleHistory) &&
                StringUtils.isNotBlank(educationLevelHistory) &&
                StringUtils.isNotBlank(degreeHistory) &&
                StringUtils.isNotBlank(station) &&
                StringUtils.isNotBlank(stationHistory)

        ){
            vo.setFinishBaseInfo(true);
        }
        if (StringUtils.isNotBlank(promise)) {
            vo.setFinishPromise(true);
        }
        if (StringUtils.isNotBlank(summary)) {
            vo.setFinishSummary(true);
        }
        vo.setFinishAllDoc(isFinishAllDoc(userId));
        return vo;
    }

    @Override
    public Result<?> isEdit(String userId) {
        SysUser user = this.getById(userId);
        //审核通过后，则不能编辑
        if (StringUtils.equals(CommonConstant.PASSED,user.getStatus())) {
            return Result.error("资料审核已通过，无法编辑！");
        }
        return null;
    }

    @Override
    public String getDeadLine() {
        return sysUserMapper.getDeadline();
    }

    @Override
    public List<DepartmentUserCount> getDepartmentUserCount() {
        List<DepartmentUserCount> result = new ArrayList<>();
        List<SysUser> nurseList = sysUserMapper.getNurseList("",dataYear);
        List<SysItem> departmentList = sysUserMapper.getDepartmentList();
        for (SysItem item : departmentList) {
            String name = item.getName();
            long count = nurseList.stream().filter(u ->StringUtils.equals(u.getDepartment(), name)).count();
            long finishedCount = nurseList.stream()
                    .filter(u -> StringUtils.equals(u.getDepartment(), name) &&
                            ("待审核".equals(u.getStatus()) || "已通过".equals(u.getStatus())))
                    .count();
            DepartmentUserCount userCount = new DepartmentUserCount();
            userCount.setName(name);
            userCount.setUserCount(count);
            userCount.setFinishedCount(finishedCount);
            result.add(userCount);
        }
        return result.stream().sorted(Comparator.comparing(DepartmentUserCount::getUserCount).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<CityUserCount> getCityUserCount() {
        return sysUserMapper.getCityUserCount();
    }


    @Override
    public List<String> getCity13List() {
        return sysUserMapper.getCity13List();
    }
}
